package com.alander.nexusgo.itinerary.controller;

import com.alander.nexusgo.common.model.dto.ItineraryListDTO;
import com.alander.nexusgo.common.model.vo.ItineraryVO;
import com.alander.nexusgo.common.response.Result;
import com.alander.nexusgo.framework.web.starter.controller.BaseController;
import com.alander.nexusgo.itinerary.model.entity.Itinerary;
import com.alander.nexusgo.itinerary.service.ItineraryService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static com.alander.nexusgo.framework.mysql.starter.page.PageUtils.getPageInfo;
import static com.alander.nexusgo.framework.mysql.starter.page.PageUtils.startPage;

/**
* 行程信息管理
*/
@RestController
@RequestMapping("/api/itineraries")
public class ItineraryController extends BaseController {
    
    @Autowired
    private ItineraryService itineraryService;
    
    /**
     * 创建行程
     */
    @PostMapping
    public Result<ItineraryVO> create(@RequestBody Itinerary itinerary) {
        try {
            ItineraryVO result = itineraryService.createItinerary(itinerary, getUserId());
            return success(result);
        } catch (Exception e) {
            return fail(e.getMessage());
        }
    }
    
    /**
     * 获取行程详情
     */
    @GetMapping("/{id}")
    public Result<ItineraryVO> get(@PathVariable(value = "id") Long id) {
        ItineraryVO itinerary = itineraryService.getItineraryById(id);
        if (itinerary == null) {
            return fail("行程不存在");
        }
        return success(itinerary);
    }
    
    /**
     * 更新行程
     */
    @PutMapping("/{id}")
    public Result<ItineraryVO> update(@PathVariable(value = "id") Long id, @RequestBody Itinerary itinerary) {
        try {
            ItineraryVO result = itineraryService.updateItinerary(id, itinerary, getUserId());
            return success(result);
        } catch (Exception e) {
            return fail(e.getMessage());
        }
    }
    
    /**
     * 删除行程
     */
    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable(value = "id") Long id) {
        try {
            boolean result = itineraryService.deleteItinerary(id, getUserId());
            if (result) {
                return success();
            } else {
                return fail("删除失败");
            }
        } catch (Exception e) {
            return fail(e.getMessage());
        }
    }
    
    /**
     * 分页查询行程列表
     */
    @GetMapping
    public PageInfo<ItineraryVO> list(@RequestBody ItineraryListDTO itineraryListDTO) {
        startPage(itineraryListDTO);
        List<ItineraryVO> itineraryVOList = itineraryService.listItineraries(itineraryListDTO);
        return getPageInfo(itineraryVOList);
    }
}